from app.libs.enums import ClientTypeEnum
from app.libs.error_code import Success
from app.libs.redprint import Redprint
from app.models.user import User
from app.validates.forms import ClientForm, UserOpenidForm,CodeForm
from app.libs.wx_auth import WxAuth
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
from app.libs.redis import Redis
import json
api = Redprint('client')

@api.route('/register',methods=['POST'])
def create_client():
    form = ClientForm().validate_for_api()
    promise = {
        ClientTypeEnum.USER_MINA: __register_user_by_openid
    }
    promise[form.type.data]()
    return Success()

@api.route('/login',methods=['POST'])
def login():
    form = ClientForm().validate_for_api()
    promise = {
        ClientTypeEnum.USER_MINA: __register_user_by_openid
    }
    promise[form.type.data]()
    return Success()


def __register_user_by_openid():
    form = UserOpenidForm().validate_for_api()
    User.register_by_openid(form.nickname.data,
                           form.openid.data,
                           form.avarat.data)

@api.route('/wx_login', methods=['GET'])
def user_info():
    token = WxAuth().wx_getToken()
    t = token
    inp_dict = json.loads(t)
    ts = inp_dict['access_token']
    Redis().set('access_token',ts)
    access_token = Redis().get('access_token')
    return access_token

    # form = CodeForm().validate_for_api()
    # url = current_app.config['WXURL'] % (current_app.config['APPID'],current_app.config['APP_SECRET'],form.code.data)
    # http = urllib3.PoolManager()
    # r =  http.request('GET',url)
    # return r.d